<template>
  <el-config-provider :locale="currentLocale">
    <router-view />
    <ReDialog />
  </el-config-provider>
</template>

<script lang="ts">
import { defineComponent, onMounted, onBeforeUnmount } from "vue";
import { ElConfigProvider } from "element-plus";
import { ReDialog } from "@/components/ReDialog";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import { SeoUtil } from "@/utils/seo";
import { useUserAuthStore } from "@/store/modules/userAuth";
import WebSocketService from "@/services/notificationWebSocket";
import { notificationService } from "@/services/notificationService";
import type { NotificationDetail, UnreadCount } from "@/api/notification";

export default defineComponent({
  name: "app",
  components: {
    [ElConfigProvider.name]: ElConfigProvider,
    ReDialog
  },
  setup() {
    const userAuthStore = useUserAuthStore();

    // 初始化SEO配置
    onMounted(async () => {
      await SeoUtil.init();

      // 如果用户已登录，连接WebSocket
      if (userAuthStore.isLoggedIn && userAuthStore.token) {
        connectWebSocket(userAuthStore.token);

        // 🔑 优化: 统一初始化通知统计数据，所有其他组件仅读取单例服务的数据
        // 这样可以避免多个组件同时请求导致的重复请求问题
        notificationService.loadStats();
      }

      // 监听登录事件
      window.addEventListener("user-login", handleUserLogin);
      // 监听登出事件
      window.addEventListener("user-logout", handleUserLogout);
      // 监听WebSocket认证错误
      window.addEventListener("websocket-auth-error", handleAuthError);
    });

    // 清理资源
    onBeforeUnmount(() => {
      // 断开WebSocket
      WebSocketService.disconnect();

      // 移除事件监听
      window.removeEventListener("user-login", handleUserLogin);
      window.removeEventListener("user-logout", handleUserLogout);
      window.removeEventListener("websocket-auth-error", handleAuthError);
    });

    /**
     * 连接WebSocket
     */
    const connectWebSocket = (token: string) => {
      WebSocketService.connect(token, {
        onNotification: handleNewNotification,
        onUnreadCount: handleUnreadCount,
        onConnect: () => {
          console.log("✅ 通知推送服务已连接");
          // 🔑 关键: 通知 notificationService WebSocket 已连接
          notificationService.setWebSocketConnected(true);
        },
        onError: error => {
          console.error("❌ 通知推送服务连接错误:", error);
          // 🔑 关键: 通知 notificationService WebSocket 已断开
          notificationService.setWebSocketConnected(false);
        },
        onClose: () => {
          console.log("🔌 通知推送服务已断开");
          // 🔑 关键: 通知 notificationService WebSocket 已断开
          notificationService.setWebSocketConnected(false);
        }
      });
    };

    /**
     * 处理新通知
     */
    const handleNewNotification = (notification: NotificationDetail) => {
      // 触发全局事件，通知UserNotification组件
      window.dispatchEvent(
        new CustomEvent("new-notification", {
          detail: notification
        })
      );
    };

    /**
     * 处理未读数量更新
     */
    const handleUnreadCount = (unreadCount: UnreadCount) => {
      // 🔑 关键: 将 WebSocket 推送的数据同步到 notificationService
      notificationService.handleWebSocketStats(unreadCount as any);

      // 触发全局事件，通知UserNotification组件
      window.dispatchEvent(
        new CustomEvent("unread-count-update", {
          detail: unreadCount
        })
      );
    };

    /**
     * 处理用户登录
     */
    const handleUserLogin = ((event: CustomEvent) => {
      const token = event.detail?.token || userAuthStore.token;
      if (token) {
        connectWebSocket(token);

        // 🔑 优化: 用户登录后加载通知统计数据
        notificationService.loadStats();
        console.log("🚀 用户登录: 已加载通知统计数据");
      }
    }) as EventListener;

    /**
     * 处理用户登出
     */
    const handleUserLogout = (() => {
      WebSocketService.disconnect();
      // 🔑 关键: 通知 notificationService WebSocket 已断开
      notificationService.setWebSocketConnected(false);
    }) as EventListener;

    /**
     * 处理WebSocket认证错误
     */
    const handleAuthError = (() => {
      console.warn("⚠️ WebSocket认证失败，请重新登录");
      // 可以在这里添加额外的处理逻辑，比如显示登录弹窗
    }) as EventListener;

    return {};
  },
  computed: {
    currentLocale() {
      return zhCn;
    }
  }
});
</script>
